import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Home from '@/views/Home.vue';
import Login from '@/views/login/Login.vue';
import Privacy from '@/views/login/AgreementsPrivacy.vue';
import AgreementsRegistproto from '@/views/login/AgreementsRegistproto.vue';
import LoginHome from '@/views/login/home/LoginHome.vue';
import Sms from '@/views/login/home/component/Sms.vue';
import Password from '@/views/login/home/component/Password.vue';
import Registration from '@/views/login/registration/Registration.vue';
import NotFound from '@/views/NotFound.vue';
import Details from '@/views/pesicideinfo/details.vue';
import { menus } from './modules/menus';
import { store } from '@/store';
/**
 * 用户是否登录
 * @return {string?} user
 */
function isLogin(): boolean {
  return !!store.token.state.accessToken;
}

// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: 'welcome',
        name: '欢迎',
        component: () => import('@/views/menus/Welcome.vue'),
      },

      ...menus,
    ],
  },

  { path: '/pesicideinfo/details/:id?', name: 'Details', component: Details },
  { path: '/:pathMatch(.*)*', component: NotFound, name: 'NotFound' },
  {
    path: '/login',
    component: Login,
    children: [
      {
        path: '',
        component: LoginHome,
        children: [
          { path: '', component: Password },
          { path: 'sms', component: Sms },
        ],
      },
      {
        path: 'registration',
        component: Registration,
      },
    ],
  },
  { path: '/login/privacy', component: Privacy },
  { path: '/login/AgreementsRegistproto', component: AgreementsRegistproto },
];
const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: createWebHashHistory(import.meta.env.BASE_URL), // createWebHistory('/pesticide-admin/'), // createWebHashHistory(),
  routes, // `routes: routes` 的缩写
});
router.beforeEach((to, from, next) => {
  console.log(to);

  if (to.path?.includes('/pesicideinfo/details/')) {
    return next();
  }
  if (to.name == 'NotFound') {
    return next();
  }
  if (!isLogin() && !to.path.includes('login')) {
    return next('/login');
  } else {
    return next();
  }
});

export default router;
